<template>
  <view style="padding: 0 30rpx 30rpx 30rpx" @touchmove.stop.prevent="() => { }">
    <slot name="top"></slot>
    <canvas
	  ref="idRef"
      class="my-canvas-cls"
      :canvas-id="canvasId"
      @touchstart.stop="touchstart"
      @touchmove.stop="touchmove"
      @touchend.stop="touchend"
    ></canvas>
    <slot name="footer"></slot>
    <view class="footer" v-if="footerShow">
      <!-- <u-button  text="保存" type="primary" @click="finish" :customStyle="{width: '33%', display: 'inline-block', lineHeight:'40px'}"></u-button> -->
      <u-button text="重写" type="warning" @click="clear" :customStyle="{width: '33%', display: 'inline-block',lineHeight:'40px'}"></u-button>
      <!-- <u-button text="关闭" type="error" @click="close" :customStyle="{width: '33%', display: 'inline-block', lineHeight:'40px'}"></u-button> -->
    </view>
  </view>
</template>
<script>
import { uploadFile } from '@/utils/request'
export default {
  data() {
    return {
      //绘图图像
      ctx: "",
      //路径点集合
      points: [],
      //签名图片
      SignatureImg: "",
	  isDrawing:false,
    };
  },
  props: {
    footerShow: {
      type: Boolean,
      default: true,
    },
	canvasId: {
		type:String,
		default: 'mycanvas-1'
	},
	imagePath: {
		type:String,
		default: ''
	}
  },
  watch: {
	  'imagePath':{
		  handler(newVal,oldVal){
			  if(newVal) {
				  this.drawCanvas()
			  }
		  },
		  deep:true,
		  immediate:true
	  }
  },
  methods: {
    // createCanvas（）----该方法主要是创建了画布
    // touchstart（）----触摸开始，获取到起点
    // touchmove（）----触摸移动，获取到路径点
    // touchend（）----触摸结束，将未绘制的点清空防止对后续路径产生干扰
    // draw（）----绘制笔迹
    // clear（）----清空画布
    // finish（）----完成绘画并保存到本地
	
	 drawCanvas() {
	  const ctx = uni.createCanvasContext(this.canvasId, this);
	  uni.downloadFile({
		url: this.imagePath,
		success: (downloadResult) => {
			console.log(downloadResult, '23333')
		  if (downloadResult.statusCode === 200) {
			ctx.drawImage(downloadResult.tempFilePath, 0, 0, 380, 160);
			ctx.draw(true, () => {
			  // 绘制完成后执行的操作
			});
		  }
		},
		fail: (error) => {
		  console.error('下载图片失败:', error);
		}
	  });
	},

    createCanvas() {
      //创建绘图对象
      this.ctx = uni.createCanvasContext(this.canvasId, this);
      //设置画笔样式
      this.ctx.lineWidth = 4;
      this.ctx.lineCap = "round";
      this.ctx.lineJoin = "round";
	  // 设置底色
	  this.ctx.fillStyle = '#f6f6f6'
	  this.ctx.fillRect(0, 0, 400, 200)
    },
    touchstart(e) {
	  this.isDrawing = true
      let startX = e.changedTouches[0].x;
      let startY = e.changedTouches[0].y;
      let startPoint = {
        X: startX,
        Y: startY,
      };
      this.points.push(startPoint);
      //每次触摸开始，开启新的路径
      this.ctx.beginPath();
    },
    touchmove(e) {
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = {
        X: moveX,
        Y: moveY,
      };
      this.points.push(movePoint); //存点
      let len = this.points.length;
      if (len >= 2) {
        this.draw(); //绘制路径
      }
    },
    touchend() {
      this.points = [];
    },
    draw() {
      let point1 = this.points[0];
      let point2 = this.points[1];
      this.points.shift();
      this.ctx.moveTo(point1.X, point1.Y);
      this.ctx.lineTo(point2.X, point2.Y);
      this.ctx.stroke();
      this.ctx.draw(true);
    },
    clear() {
      let that = this;
      uni.getSystemInfo({
        success: (res) => {
          let canvasw = res.windowWidth;
          let canvash = res.windowHeight;
          that.ctx.clearRect(0, 0, canvasw, canvash);
		  // 设置底色
		  this.ctx.fillStyle = '#f6f6f6'
		  this.ctx.fillRect(0, 0, 400, 200)
          that.ctx.draw(true);
          this.$emit("clearPath");
        },
      });
    },
    finish() {
		if(this.isDrawing) {
			return new Promise(resolve => {
				let that = this;
				uni.canvasToTempFilePath({
				  canvasId: this.canvasId,
				  success: (res) => {	
					resolve(res.tempFilePath)
				  },
				},that);
			})
		}
    },
    close() {
      this.$emit("close");
    },
  },
  mounted() {
    this.createCanvas();
  },
};
</script>
<style lang="less" scoped>
.bigbox {
  touch-action: none;
}

.my-canvas-cls {
  height: 300rpx;
  width: 100%;
  display: block;
  position: relative;
  background: #f6f6f6;
}

.footer {
  font-size: 14px;
  height: 150upx;
  display: flex;
  justify-content: space-around;
  align-items: center;
  // padding-left: 40rpx;

  .left {
    background-color: #ecf5ff;
    color: #a0cfff;
    border-radius: 8rpx;
    padding: 10rpx 15rpx;
    border: 1px solid #a0cfff;
  }
  .right {
    background-color: #fdf6ec;
    color: #fcbd71;
    border-radius: 8rpx;
    padding: 10rpx 15rpx;
    border: 1px solid #fcbd71;
  }
  .close {
    background-color: #fef0f0;
    color: #fab6b6;
    border-radius: 8rpx;
    padding: 10rpx 15rpx;
    border: 1px solid #fab6b6;
  }
}

.but-class {
  margin-right: 40rpx;
}
</style>